package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.domain.ClientTransfer;
import cn.wolfcode.crm.domain.LatentClient;
import cn.wolfcode.crm.query.ClientTransferQueryObject;
import cn.wolfcode.crm.query.PageResult;
import cn.wolfcode.crm.service.IClientTransferService;
import cn.wolfcode.crm.service.ILatentClientService;
import cn.wolfcode.crm.util.JsonResult;
import cn.wolfcode.crm.util.UserContext;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;


@Controller
@RequestMapping("clientTransfer")
public class ClientTransferController {

	@Autowired
	private IClientTransferService service;
	@Autowired
	private ILatentClientService latentClientService;

	@RequestMapping("view")
	@RequiresPermissions(value = {"clientTransfer:view", "查看客户转移记录界面"}, logical = Logical.OR)
	public String view() {
        //返回到客户转移记录界面
		return "/clienttransfer/list";
	}

	@RequiresPermissions(value = {"clientTransfer:query", "查看客户转移记录"}, logical = Logical.OR)
	@RequestMapping("query")
	@ResponseBody
    //查询客户转移记录
	public PageResult query(ClientTransferQueryObject qo){

		return service.query(qo);
	}



    @RequestMapping({"deleteLatentClient"})
    @ResponseBody
    //删除客户端
    public JsonResult deleteLatentClient(Long id) {
        JsonResult result = new JsonResult();
        try {
            this.latentClientService.deleteByPrimaryKey(id);
            //默认是保存成功
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            //否则保存失败
            return result.mark("保存失败");
        }
    }

    @RequestMapping({"transfer"})
    @ResponseBody
    public JsonResult transform(Long id, ClientTransfer transfer) {
        JsonResult result = new JsonResult();
        try {
            LatentClient latentClient = this.latentClientService.selectByPrimaryKey(id);
            //设置客户对象
            transfer.setLatentClient(latentClient);
            //设置管理员
            transfer.setTransUser(UserContext.getCurrentUser());
            //设置时间
            transfer.setTransTime(new Date());
            //设置原市场专员
            transfer.setOldSeller(latentClient.getInChargeUser());
            //保存客户转移
            this.service.insert(transfer);
            //改变状态为移交客户状态
            this.latentClientService.changeStateTransfer(id);
            //默认为操作成功
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return result.mark("移交失败");
        }
    }
}
